package com.zhou.framework.xss.request;

import com.zhou.util.StringTool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }
    @Override
    public String getParameter(String name) {
        return toSafeValue(super.getParameter(name));
    }
    @Override
    public Map<String,String[]> getParameterMap() {
        Map<String, String[]> result = new HashMap<>();
        Enumeration<String> parameterNames = super.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String parameterName = parameterNames.nextElement();
            result.put(parameterName, new String[]{toSafeValue(super.getParameter(parameterName))});
        }
        return result;
    }
    @Override
    public String getHeader(String name) {
        return toSafeValue(super.getHeader(name));
    }
    private String toSafeValue(String value){
        if(value != null && value.length() > 0){
            //value = Jsoup.clean(value, Whitelist.relaxed()).trim();
            value = StringTool.removeHtml(value);
        }
        return value;
    }
    @Override
    public String[] getParameterValues(String name)
    {
        String[] values = super.getParameterValues(name);
        if (values != null){
            int length = values.length;
            String[] escapseValues = new String[length];
            for (int i = 0; i < length; i++) {
                // 防xss攻击和过滤前后空格
                escapseValues[i] = toSafeValue(values[i]);
            }
            return escapseValues;
        }
        return values;
    }

}
